package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.mall.order.dto.PayOrderSuccessRequest;
import com.cskaoyan.mall.order.dto.PayOrderSuccessResponse;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderCoreService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderConverter orderConverter;

    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest request) {
        CreateOrderResponse response = new CreateOrderResponse();
        try {
            //创建pipeline对象
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）

            //获取处理结果
            AbsTransHandlerContext context = invoker.getContext();

            //把处理结果转换为response
            response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);

        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
        CancelOrderResponse response = new CancelOrderResponse();
        String orderId = request.getOrderId();
        boolean cancel = cancelOrder(orderId);

        response.setCode(OrderRetCode.SUCCESS.getCode());
        response.setMsg(OrderRetCode.SUCCESS.getMessage());

        return response;
    }

    public boolean cancelOrder(String orderId){
        // 查询商品订单
        try {
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId",orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);


            for (OrderItem orderItem : orderItems) {
                Long itemId = orderItem.getItemId();
                Integer num = orderItem.getNum();
                // 更改锁定库存
                Stock stock = new Stock();
                stock.setItemId(itemId);
                stock.setLockCount(-num);
                stock.setStockCount(num.longValue());
                stockMapper.updateStock(stock);
                // 更改订单商品状态
                orderItemMapper.updateStockStatus(2,orderItem.getOrderId());
            }

            // 更改订单状态
            updateOrder(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL, orderId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    @Override
    public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {
        String orderId = request.getOrderId();
        int deleted = 0;
        // 删除订单商品表
        Example example = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId", orderId);
        deleted = orderItemMapper.deleteByExample(example);
        // 删除物流信息表
        deleted = orderShippingMapper.deleteByPrimaryKey(orderId);
        // 删除订单表
        deleted = orderMapper.deleteByPrimaryKey(orderId);

        DeleteOrderResponse response = new DeleteOrderResponse();
        response.setCode(OrderRetCode.SUCCESS.getCode());
        response.setMsg(OrderRetCode.SUCCESS.getMessage());

        return response;
    }

    /**
     * @Description: 铲鲟用户所有的订单
     * @Author: cuiweiguo#
     * @Date: 2022/5/20 19:46
     * @Param: [orderListRequest]:
     * @return: com.cskaoyan.order.dto.OrderListResponse:
     **/
    public OrderListResponse queryOrdersByUserId(OrderListRequest orderListRequest) {
        OrderListResponse orderListResponse = new OrderListResponse();
        //新开启分页
        Integer page = orderListRequest.getPage();
        Integer size = orderListRequest.getSize();
        String sort = "create_time desc";//排序列
        //String order = "desc";//desc\asc
        PageHelper.startPage(page,size,sort);
        //查询数据库
        Example example = new Example(Order.class);
        example.createCriteria()
                .andEqualTo("userId", orderListRequest.getUserId());
        List<Order> orders = orderMapper.selectByExample(example);
        //将orderlist转化为orderDetailInfo
        List<OrderDetailInfo> orderDetailInfos = orderConverter.order2detailList(orders);
        PageInfo<Order> pageInfo = new PageInfo<>(orders);
        long total = pageInfo.getTotal();
        //long total = orderMapper.selectCountByExample(example);
        //获得所有的用户点单之后 ，根据订单的id，查询关联表
        for (OrderDetailInfo orderDetailInfo : orderDetailInfos) {
            //先查询商品关联表的信息
            String orderId = orderDetailInfo.getOrderId();
            Example exampleOrderItem = new Example(OrderItem.class);
            exampleOrderItem.createCriteria()
                    .andEqualTo("orderId",orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(exampleOrderItem);
            List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
            orderDetailInfo.setOrderItemDto(orderItemDtos);
            //再查询快递关联表信息
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);
            OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
            orderDetailInfo.setOrderShippingDto(orderShippingDto);
        }
        orderListResponse.setData(orderDetailInfos);
        orderListResponse.setTotal(total);
        return orderListResponse;
    }

    @Override
    public void updateOrder(Integer status, String orderId) {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(status);
        order.setUpdateTime(new Date());
        int update = orderMapper.updateByPrimaryKeySelective(order);
    }
}
